import { defineStore } from 'pinia'

export interface Memory {
  id: number
  title: string
  content: string
  createTime: string
  updateTime?: string
  images: string[]
  hasAudio: boolean
  hasVideo: boolean
  mediaList?: Array<{
    type: 'image' | 'video' | 'audio' | 'file'
    url: string
    name?: string
    size?: string
    duration?: string
    fileType?: string
    poster?: string
  }>
}

export interface Folder {
  folderId: string
  folderName: string
  createTime: string
  updateTime?: string
  memorial: Memory[]
}

export interface UserInfo {
  name: string
  avatar: string
  color: string
  isPinned?: boolean
}

export interface UserData {
  userInfo: UserInfo
  id: string | number
  folders: Folder[]
}

interface State {
  initialized: boolean
  currentUser: string | number | null
  users: Record<string | number, UserData>
}

// Storage Key
const STORAGE_KEY = 'user-memories'

export const useMemoriesStore = defineStore('memories', {
  state: (): State => ({
    initialized: false,
    currentUser: null,
    users: {},
  }),

  getters: {
    currentUserData(): UserData | null {
      if (!this.currentUser) return null
      return this.users[this.currentUser] || null
    },

    folders(): Folder[] {
      if (!this.currentUserData?.folders) return []
      return this.currentUserData.folders.filter((f) => f.folderId !== 'default')
    },

    defaultMemories(): Memory[] {
      if (!this.currentUserData?.folders) return []
      const defaultFolder = this.currentUserData.folders.find((f) => f.folderId === 'default')
      return defaultFolder?.memorial || []
    },

    allFolders(): Folder[] {
      return this.currentUserData?.folders || []
    },
  },

  actions: {
    async init() {
      if (this.initialized) return

      try {
        const data = uni.getStorageSync('memories')
        if (data) {
          const parsed = JSON.parse(data)
          this.users = parsed.users || {}
          this.currentUser = parsed.currentUser
        }
        this.initialized = true
      } catch (error) {
        console.error('Failed to initialize memories store:', error)
      }
    },

    setCurrentUser(id: string | number, userInfo?: UserInfo) {
      this.currentUser = id
      // 如果用户不存在，初始化用户数据
      if (!this.users[id]) {
        this.users[id] = {
          userInfo: userInfo || {
            name: '新娃娃',
            avatar: '',
            color: '#60a5fa',
          },
          id,
          folders: [
            {
              folderId: 'default',
              folderName: '默认文件夹',
              createTime: new Date().toISOString(),
              updateTime: new Date().toISOString(),
              memorial: [],
            },
          ],
        }
      }
      this.save()
    },

    async save() {
      try {
        const dataToSave = {
          users: this.users,
          currentUser: this.currentUser,
          initialized: this.initialized,
        }
        uni.setStorageSync('memories', JSON.stringify(dataToSave))
      } catch (error) {
        console.error('Failed to save memories:', error)
      }
    },

    async refresh() {
      try {
        const data = uni.getStorageSync('memories')
        if (data) {
          const parsed = JSON.parse(data)
          // 只更新数据，保持初始化状态
          if (parsed.users) {
            this.users = parsed.users
          }
          if (parsed.currentUser !== undefined) {
            this.currentUser = parsed.currentUser
          }
        }
      } catch (error) {
        console.error('Failed to refresh memories:', error)
      }
    },

    // 创建文件夹
    createFolder(name: string, color: string) {
      if (!this.currentUser || !this.currentUserData) return null

      const newFolder: Folder = {
        folderId: Date.now().toString(),
        folderName: name.trim(),
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        memorial: [],
      }

      this.currentUserData.folders.push(newFolder)
      this.save()
      return newFolder
    },

    // 获取文件夹中的回忆
    getFolderMemories(folderId: string): Memory[] {
      return this.currentUserData?.folders.find((f) => f.folderId === folderId)?.memorial || []
    },

    // 获取单个回忆
    getMemory(memoryId: number): Memory | null {
      if (!this.currentUserData) return null

      for (const folder of this.currentUserData.folders) {
        const memory = folder.memorial.find((m) => m.id === memoryId)
        if (memory) return memory
      }
      return null
    },

    // 删除回忆
    deleteMemory(memoryId: number) {
      if (!this.currentUserData) return

      for (const folder of this.currentUserData.folders) {
        const index = folder.memorial.findIndex((m) => m.id === memoryId)
        if (index > -1) {
          folder.memorial.splice(index, 1)
          folder.updateTime = new Date().toISOString()
          this.save()
          break
        }
      }
    },

    // 删除文件夹
    deleteFolder(folderId: string) {
      if (!this.currentUserData || folderId === 'default') return

      const index = this.currentUserData.folders.findIndex((f) => f.folderId === folderId)
      if (index > -1) {
        this.currentUserData.folders.splice(index, 1)
        this.save()
      }
    },

    // 添加更新回忆的方法
    updateMemory(memoryId: number, data: Partial<Memory>) {
      if (!this.currentUserData) return

      for (const folder of this.currentUserData.folders) {
        const memoryIndex = folder.memorial.findIndex((m) => m.id === memoryId)
        if (memoryIndex > -1) {
          folder.memorial[memoryIndex] = {
            ...folder.memorial[memoryIndex],
            ...data,
            updateTime: new Date().toISOString(),
          }
          folder.updateTime = new Date().toISOString()
          this.save()
          break
        }
      }
    },

    // 添加创建回忆的方法
    createMemory(title: string, folderId: string = 'default') {
      if (!this.currentUser || !this.currentUserData) return null

      const folder = this.currentUserData.folders.find((f) => f.folderId === folderId)
      if (!folder) return null

      const newMemory: Memory = {
        id: Date.now(),
        title,
        content: '',
        createTime: new Date().toISOString(),
        updateTime: new Date().toISOString(),
        images: [],
        hasAudio: false,
        hasVideo: false,
        mediaList: [],
      }

      folder.memorial.push(newMemory)
      folder.updateTime = new Date().toISOString()
      this.save()
      return newMemory
    },
  },
})
